<template>
    <div className="total-charge-chart" ref="chartRef"></div>
</template>

<script>
import * as echarts from 'echarts';
import request from "@/utils/request";

export default {
    name: 'TotalChargeChart',
    data() {
        return {
            myChart: null,
            chartData: [], // 总电量历史数据
            maxDataCount: 20, // 最多显示20个数据点
            requestInterval: null,
            lineColor: '#2196f3' // 总电量线条颜色（与多电器图表配色协调）
        };
    },
    mounted() {
        this.initChart();
        this.startRequest();
    },
    beforeUnmount() {
        // 清理资源
        if (this.requestInterval) clearInterval(this.requestInterval);
        if (this.myChart) this.myChart.dispose();
        window.removeEventListener('resize', this.handleResize);
    },
    methods: {
        initChart() {
            const chartDom = this.$refs.chartRef;
            this.myChart = echarts.init(chartDom);
            this.myChart.setOption(this.getChartOption());
            window.addEventListener('resize', this.handleResize);
        },

        handleResize() {
            if (this.myChart) this.myChart.resize();
        },

        getChartOption() {
            return {
                title: {
                    text: '实时总电量监测',
                    left: 'center',
                    textStyle: {color: '#333', fontSize: 15}
                },
                tooltip: {
                    trigger: 'item',
                    triggerOn: 'mousemove',
                    axisPointer: {
                        type: 'line',
                        lineStyle: {
                            color: this.lineColor,
                            width: 1,
                            type: 'dashed'
                        }
                    },
                    formatter: this.formatTooltip,
                    padding: 10,
                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                    borderColor: this.lineColor,
                    borderWidth: 1,
                    textStyle: {fontSize: 12},
                    zIndex: 9999
                },
                xAxis: {
                    type: 'time',
                    splitLine: {show: false},
                    axisLabel: {
                        formatter: '{hh}:{mm}:{ss}',
                        color: '#666'
                    },
                    axisLine: {lineStyle: {color: '#eee'}}
                },
                yAxis: {
                    type: 'value',
                    boundaryGap: [0, '10%'],
                    splitLine: {
                        show: true,
                        lineStyle: {color: 'rgba(240, 240, 240, 0.5)'}
                    },
                    name: '总电量 (kWh)',
                    nameTextStyle: {
                        margin: 10,
                        color: '#333',
                        fontSize: 13
                    },
                    axisLabel: {color: '#666'},
                    axisLine: {lineStyle: {color: '#eee'}}
                },
                series: [{
                    id: 'total_charge',
                    name: '总电量',
                    type: 'line',
                    showSymbol: false,
                    smooth: true,
                    lineStyle: {width: 2, color: this.lineColor},
                    emphasis: {
                        lineStyle: {width: 4, color: `${this.lineColor}ff`}
                    },
                    data: this.chartData,
                    triggerLineEvent: true
                }],
                grid: {
                    left: '8%',
                    right: '5%',
                    bottom: '15%',
                    top: '10%',
                    backgroundColor: 'transparent'
                }
            };
        },

        formatTooltip(params) {
            const {value, color} = params;
            const date = new Date(value[0]);
            const timeStr = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
            return `
                <div style="display: flex; align-items: center; margin-bottom: 4px;">
                    <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${color}; margin-right: 6px;"></span>
                    <strong style="color: #333;">总电量</strong>
                </div>
                <div style="color: #666; font-size: 11px;">时间：${timeStr}</div>
                <div style="color: #333; font-weight: 500;">累计电量：${value[1].toFixed(2)} kWh</div>
            `;
        },

        startRequest() {
            this.fetchTotalChargeData(); // 立即执行一次
            this.requestInterval = setInterval(() => this.fetchTotalChargeData(), 1000); // 每秒请求
        },

        async fetchTotalChargeData() {
            try {
                const response = await request.get('/api/meter/latest');
                if (response.data.code !== '200' || !response.data.data) {
                    console.warn('总电量接口返回数据异常', response.data);
                    return;
                }

                const {totalCharge} = response.data.data; // 仅获取总电量数值
                const currentTime = new Date().toISOString(); // 获取**当前系统实时时间**
                const dataPoint = [currentTime, totalCharge];

                // 添加新数据，控制数据量
                this.chartData.push(dataPoint);
                if (this.chartData.length > this.maxDataCount) {
                    this.chartData.shift();
                }

                this.updateChart();
            } catch (error) {
                console.error('获取总电量数据失败', error);
            }
        },

        updateChart() {
            if (this.myChart) {
                const option = this.getChartOption();
                this.myChart.setOption(option, true);
            }
        }
    }
};
</script>

<style scoped>
.total-charge-chart {
    width: 100%;
    height: 350px; /* 与多电器图表高度协调 */
    margin-bottom: 30px; /* 与下方多电器图表间距 */
}

::v-deep .echarts-tooltip {
    border-radius: 4px !important;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}
</style>